package com.stu.stusystem.service.system;

import com.stu.stusystem.common.ApiException;
import com.stu.stusystem.mapper.system.RoleJurisdictionMapper;
import com.stu.stusystem.model.em.TreeModel;
import com.stu.stusystem.model.system.RoleJurisdiction;
import com.stu.stusystem.util.TreeModelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: cxt
 * @time: 2021/3/31
 */
@Service
public class RoleJurisdictionService {

    private RoleJurisdictionMapper roleJurisdictionMapper;

    /**
     * 根据角色id查询权限
     *
     * @param id 角色id
     */
    public List<Object> getRoleJurisdiction(String id) {
        List<TreeModel> roleJurisdiction = this.roleJurisdictionMapper.getRoleJurisdiction(id);
        return TreeModelUtil.buildTreeList(roleJurisdiction, "pid");
    }

    /**
     * 授权
     *
     * @param id     角色id
     * @param menuId 菜单id
     */
    public void authorization(String id, String[] menuId) {
        if (menuId.length == 0) {
            throw new ApiException("权限id不能为空");
        }
        this.roleJurisdictionMapper.deleteByPrimaryKey(id);
        ArrayList<RoleJurisdiction> list = new ArrayList<>();
        for (String s : menuId) {
            RoleJurisdiction roleJurisdiction = new RoleJurisdiction(id, s);
            list.add(roleJurisdiction);
        }
        int i = this.roleJurisdictionMapper.insertList(list);
        if (i == 0) {
            throw new ApiException(ApiException.SAVE_FAIL);
        }
    }

    @Autowired
    public void setRoleJurisdictionMapper(RoleJurisdictionMapper roleJurisdictionMapper) {
        this.roleJurisdictionMapper = roleJurisdictionMapper;
    }
}
